﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SharedFizzBuzz
{
    public class VariableFizzBuzzStrategy : IFizzBuzzStrategy
    {
        private string[] tokens;
        private int[] divisors;

        public VariableFizzBuzzStrategy(string[] tokens, int[] divisors)
        {
            if (tokens == null) throw new ArgumentNullException("tokens");
            if (divisors == null) throw new ArgumentNullException("divisors");
            if (tokens.Length == 0) throw new ArgumentException("The tokens and divisors arrays can not be empty.");
            if (tokens.Length != divisors.Length) throw new ArgumentException("The tokens and divisors arrays must be of equal length");
            if (divisors.Contains(0)) throw new ArgumentException("The value 0 is not a valid divisor.", "divisors");
            if (tokens.Contains(null)) throw new ArgumentNullException("NULL is not a valid token value.");

            foreach (var token in tokens)
            {
                if (String.IsNullOrWhiteSpace(token)) throw new ArgumentException("An empty or all whitespace value is not a valid token value.");                
            }   
                
            this.tokens = tokens;
            this.divisors = divisors;
        }

        public string Transform(int i)
        {
            var tokenBuilder = new StringBuilder();

            for (int j = 0; j < divisors.Length; j++)
            {
                if (i % divisors[j] == 0)
                {
                    tokenBuilder.Append(tokens[j]);
                }
            }

            if (tokenBuilder.Length == 0)
            {
                tokenBuilder.Append(i);
            }

            return tokenBuilder.ToString();
        }
    }
}
